package com.sduept.nwld.dataserver.controller.dataview;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxACLineSegment;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxBaseEntity;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxBreaker;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxBusbarsection;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxFaultRecordEquipment;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxPowertransformer;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxProtectionEquipment;
import com.sduept.nwld.dataserver.model.edata.cim.bx.BxSubstation;
import com.sduept.nwld.dataserver.util.LibTreeNode;

@Named
@ViewScoped
public class BxModelController extends AbstractController {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5552779308770511020L;
	@Autowired
	private FaultSystemProperties pros;
	@Autowired
	private SuperDAO dao;
	private TreeNode root;
	private TreeNode currentSelect;

	public static final String TREETYPE = "1";
	private String filterStation;

	private String svgContent;

	private String selectedSid;
	private String selectedSname;

	private String selectFid;
	private String selectFname;

	@PostConstruct
	private void init() {
		initTree();

	}

	public void initTree() {
		root = new DefaultTreeNode();
		List<BxSubstation> roots = dao.findAll(BxSubstation.class);
		genStationTreeNode(roots);
	}

	public void clearSelectedDMF() {
		if (StringUtils.isEmpty(selectFid)) {
			alertErrorMessage("请选中一个录波器！");
		} else {
			try {
				dao.nativeUpdate(
						"update t_cim_waverecord_equipment t set t.cfg=null,t.dmf=null,t.cfg_file=null,t.dmf_file=null where t.id='"
								+ selectFid + "'");
				addSuccessMessage("清除成功！");
			} catch (Exception e) {
				alertErrorMessage(e.getMessage());
			}
		}
	}

	public void filterTree(String id) {
		root = new DefaultTreeNode();
		List<BxSubstation> roots = dao.findByCondition("stationid=?", new Object[] { id }, BxSubstation.class);
		genStationTreeNode(roots);
	}

	private void genStationTreeNode(List<BxSubstation> roots) {
		for (BxSubstation sub : roots) {
			LibTreeNode subNode = new LibTreeNode(BxSubstation.class.getSimpleName(), sub, root);
			new LibTreeNode(TREETYPE, new DirNode(sub.getStationid(), "录波器", sub.getCimId()), subNode);
			new LibTreeNode(TREETYPE, new DirNode(sub.getStationid(), "断路器", sub.getCimId()), subNode);
			new LibTreeNode(TREETYPE, new DirNode(sub.getStationid(), "母线", sub.getCimId()), subNode);
			new LibTreeNode(TREETYPE, new DirNode(sub.getStationid(), "变压器", sub.getCimId()), subNode);
			new LibTreeNode(TREETYPE, new DirNode(sub.getStationid(), "线路", sub.getCimId()), subNode);
		}
	}

	public TreeNode getTreeNodeResource() {
		return root;
	}

	public void onNodeExpand(NodeExpandEvent event) {
		TreeNode currentNode = event.getTreeNode();
		if (currentNode.getData() instanceof DirNode) {
			DirNode currentObj = (DirNode) currentNode.getData();
			if ("线路".equals(currentObj.name)) {
//				List<BxACLineSegment> acs = dao.findByCondition("stationid='" + currentObj.id + "'",
//						BxACLineSegment.class);
				List<BxACLineSegment> acs = dao.findByCondition(BxACLineSegment.class, "stationid= ?", currentObj.id);
				for (BxACLineSegment bean : acs) {
					new LibTreeNode(TREETYPE, bean, currentNode);
				}
			} else if ("断路器".equals(currentObj.name)) {
//				List<BxBreaker> acs = dao.findByCondition("stationid='" + currentObj.id + "'", BxBreaker.class);
				List<BxBreaker> acs = dao.findByCondition(BxBreaker.class, "stationid = ?", currentObj.id);
				for (BxBreaker bean : acs) {
					new LibTreeNode(TREETYPE, bean, currentNode);
				}
			} else if ("母线".equals(currentObj.name)) {
//				List<BxBusbarsection> acs = dao.findByCondition("stationid='" + currentObj.id + "'",
//						BxBusbarsection.class);
				List<BxBusbarsection> acs = dao.findByCondition(BxBusbarsection.class, "stationid= ?", currentObj.id);
				for (BxBusbarsection bean : acs) {
					new LibTreeNode(TREETYPE, bean, currentNode);
				}
			} else if ("变压器".equals(currentObj.name)) {
//				List<BxPowertransformer> acs = dao.findByCondition("stationid='" + currentObj.id + "'",
//						BxPowertransformer.class);
				List<BxPowertransformer> acs = dao.findByCondition(BxPowertransformer.class, "stationid= ?",
						BxPowertransformer.class);
				for (BxPowertransformer bean : acs) {
					new LibTreeNode(TREETYPE, bean, currentNode);
				}
			} else if ("录波器".equals(currentObj.name)) {
//				List<BxFaultRecordEquipment> acs = dao.findByCondition("stationId='" + currentObj.cimId + "'",
//						BxFaultRecordEquipment.class);
				List<BxFaultRecordEquipment> acs = dao.findByCondition(BxFaultRecordEquipment.class, "stationId=?",
						currentObj.cimId);
				for (BxFaultRecordEquipment bean : acs) {
					new DefaultTreeNode("lbq", bean, currentNode);
				}
			}
		} else if (currentNode.getData() instanceof BxBaseEntity) {
			BxBaseEntity project = (BxBaseEntity) currentNode.getData();
//			List<BxProtectionEquipment> beans = dao.findByCondition("mPrimdevID='" + project.getMid() + "'",
//					BxProtectionEquipment.class);
			List<BxProtectionEquipment> beans = dao.findByCondition(BxProtectionEquipment.class, "mPrimdevID=?",
					project.getMid());
			for (BxProtectionEquipment b : beans) {
				new DefaultTreeNode(BxProtectionEquipment.class.getSimpleName(), b, currentNode);
			}
		}
	}

	// 事件
	public void onNodeSelect(NodeSelectEvent event) {
		currentSelect = event.getTreeNode();
		if (currentSelect != null) {
			if ("BxSubstation".equals(currentSelect.getType())) {
				BxSubstation sub = (BxSubstation) currentSelect.getData();
				genSvgContent(sub.getCimId());
				selectedSid = sub.getCimId();
			} else if ("lbq".equals(currentSelect.getType())) {
				BxFaultRecordEquipment sub = (BxFaultRecordEquipment) currentSelect.getData();
				selectFid = sub.getId();
				selectFname = sub.getName();
				selectedSid = sub.getStationID();
				selectedSname = sub.getStationName();
			}
		}

	}

	public void autoCompleteStation(SelectEvent event) {
		Object item = event.getObject();
		if (null != item) {
			filterTree(item.toString());
		}
	}

	public TreeNode getCurrentSelect() {
		return currentSelect;
	}

	public TreeNode getRoot() {
		return root;
	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}

	public void setCurrentSelect(TreeNode currentSelect) {
		this.currentSelect = currentSelect;
	}

	public class DirNode {
		public String id;
		public String name;
		public String cimId;

		@Override
		public String toString() {
			return name;
		}

		public DirNode(String id, String name, String cimId) {
			this.id = id;
			this.name = name;
			this.cimId = cimId;
		}
	}

	public String getFilterStation() {
		return filterStation;
	}

	public void setFilterStation(String filterStation) {
		this.filterStation = filterStation;
	}

	private void genSvgContent(String stationId) {
		StringBuffer sb = new StringBuffer();
		File sf = new File(pros.getSvgBxPath() + stationId + ".svg");
		if (sf.exists()) {
			RandomAccessFile raf = null;
			try {
				raf = new RandomAccessFile(sf, "r");
				String lstr = raf.readLine();
				boolean startAdd = false;
				while (lstr != null) {
					if (startAdd) {
						lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
						lstr = lstr.replaceAll("\"", "'");
//						if(lstr.startsWith("<text")){
//							lstr = lstr.replaceFirst("<text", "<text onclick='alert(this)' ");
//						}
						sb.append(lstr);
					} else {
						if (lstr.startsWith("<svg")) {
							startAdd = true;
							lstr = new String(lstr.trim().getBytes("ISO-8859-1"), "utf-8");
							lstr = lstr.replaceAll("\"", "'");
							sb.append(lstr);
						}
					}
					lstr = raf.readLine();
				}
				svgContent = sb.toString();
//				log.info(svgContent);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

	public String getSvgContent() {
		return svgContent;
	}

	public void setSvgContent(String svgContent) {
		this.svgContent = svgContent;
	}

	public String getSelectedSid() {
		return selectedSid;
	}

	public void setSelectedSid(String selectedSid) {
		this.selectedSid = selectedSid;
	}

	public String getSelectFid() {
		return selectFid;
	}

	public void setSelectFid(String selectFid) {
		this.selectFid = selectFid;
	}

	public String getSelectedSname() {
		return selectedSname;
	}

	public void setSelectedSname(String selectedSname) {
		this.selectedSname = selectedSname;
	}

	public String getSelectFname() {
		return selectFname;
	}

	public void setSelectFname(String selectFname) {
		this.selectFname = selectFname;
	}
}
